//
//  MenuData.swift
//  
//
//  Created by 孙长坦 on 2022/6/17.
//

import Foundation

public struct MenuData: Codable {
    enum CodingKeys: CodingKey {
        case id
        case icon
        case title
        case enabled
        case url
        case onTap
        case children
        case style
    }
    
    public let id: String
    public let icon: String?
    public let title: String?
    public let enabled: Bool
    public let url: String?
    public let onTap: String?
    public var children: [MenuData]?
    public let style: StyleData?
    public weak var webView: WKWebViewEx?
    
    public init(id: String = UUID().uuidString,
                icon: String? = nil,
                title: String? = nil,
                enabled: Bool = true,
                url: String? = nil,
                onTap: String? = nil,
                children: [MenuData]? = nil,
                style: StyleData? = nil) {
        self.id = id
        self.icon = icon
        self.title = title
        self.enabled = enabled
        self.url = url
        self.onTap = onTap
        self.children = children
        self.style = style
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        id = (try? container.decodeIfPresent(String.self, forKey: .id)) ?? UUID().uuidString
        icon = try? container.decodeIfPresent(String.self, forKey: .icon)
        title = try? container.decodeIfPresent(String.self, forKey: .title)
        enabled = (try? container.decodeIfPresent(Bool.self, forKey: .enabled)) ?? true
        url = try? container.decodeIfPresent(String.self, forKey: .url)
        onTap = try? container.decodeIfPresent(String.self, forKey: .onTap)
        children = try? container.decodeIfPresent([MenuData].self, forKey: .children)
        style = try? container.decodeIfPresent(StyleData.self, forKey: .style)
    }
}

